package com.example.studyktdemo.viewmodel

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.studyktdemo.bean.FocusOnBean
import com.example.studyktdemo.bean.HomeBean
import com.google.gson.Gson
import okhttp3.*
import java.io.IOException
import java.net.HttpURLConnection

class FocusOnViewModel : ViewModel() {

    private val TAG = "FocusOnViewModel"

    private var focusMutableLiveData: MutableLiveData<FocusOnBean> = MutableLiveData()

    fun getFocusMutableLiveData(): MutableLiveData<FocusOnBean>? {
        return focusMutableLiveData
    }

    fun queryFocusInfo() {
        var client = OkHttpClient()
        var request = Request.Builder().url("https://baobab.kaiyanapp.com/api/v4/tabs/follow")
            .get().build()
        var call = client.newCall(request)

        call.enqueue(object : Callback {
            override fun onResponse(call: Call?, response: Response?) {
                var code = response?.code()
                Log.d(TAG, "code---> $code")
                if (code == HttpURLConnection.HTTP_OK) {
                    var result = response?.body()?.string()
                    var data = Gson().fromJson(result, FocusOnBean::class.java)

                    if (data != null) {
                        focusMutableLiveData.postValue(data)
                    } else {
                        focusMutableLiveData.postValue(null)
                    }
                    //Log.d(TAG,"homeData----> $homeData")
                }
            }

            override fun onFailure(call: Call?, e: IOException?) {
                Log.d(TAG, "e---> ${e.toString()}")
            }
        })
    }
}